package com.cencat.user.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cencat.common.response.PageResponse;
import com.cencat.common.exception.BusinessException;
import com.cencat.common.response.ApiResponse;
import com.cencat.common.enums.UserStatus;
import com.cencat.user.dto.UserCreateDTO;
import com.cencat.user.dto.UserUpdateDTO;
import com.cencat.user.dto.UserQueryDTO;
import com.cencat.user.dto.LoginDTO;
import com.cencat.user.dto.TokenDTO;
import com.cencat.user.dto.LogoutDTO;
import com.cencat.user.entity.User;
import com.cencat.user.service.UserService;
import com.cencat.user.vo.UserVO;
import com.cencat.user.vo.UserListVO;
import com.cencat.user.vo.LoginVO;
import com.cencat.user.vo.TokenVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import java.util.List;

/**
 * 用户管理控制器
 * 提供用户的增删改查、状态管理、密码管理等功能
 * 支持多租户架构，所有操作都基于租户隔离
 * 
 * @author cencat
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/api/user")
@Tag(name = "用户管理", description = "用户管理相关接口，支持多租户架构")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * 
     * @param dto 登录DTO
     * @return 登录结果
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录认证，返回访问令牌")
    public ApiResponse<LoginVO> login(@Valid @RequestBody LoginDTO dto) {
        try {
            LoginVO loginVO = userService.login(dto);
            log.info("用户登录成功: username={}, loginIp={}, tenantId={}", dto.getUsername(), dto.getLoginIp(), dto.getTenantId());
            return ApiResponse.success(loginVO);
        } catch (BusinessException e) {
            log.error("用户登录失败: username={}, loginIp={}, tenantId={}, error={}", dto.getUsername(), dto.getLoginIp(), dto.getTenantId(), e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("用户登录异常: username={}, loginIp={}, tenantId={}, error={}", dto.getUsername(), dto.getLoginIp(), dto.getTenantId(), e.getMessage(), e);
            return ApiResponse.error(500, "系统异常，请稍后重试");
        }
    }

    /**
     * 用户登出
     * 
     * @param dto 登出DTO
     * @return 登出结果
     */
    @PostMapping("/logout")
    @Operation(summary = "用户登出", description = "用户登出，清除访问令牌")
    public ApiResponse<Boolean> logout(@Valid @RequestBody LogoutDTO dto) {
        try {
            Boolean result = userService.logout(dto);
            log.info("用户登出成功: userId={}, clientIp={}, tenantId={}", dto.getUserId(), dto.getClientIp(), dto.getTenantId());
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("用户登出失败: userId={}, clientIp={}, tenantId={}, error={}", dto.getUserId(), dto.getClientIp(), dto.getTenantId(), e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("用户登出异常: userId={}, clientIp={}, tenantId={}, error={}", dto.getUserId(), dto.getClientIp(), dto.getTenantId(), e.getMessage(), e);
            return ApiResponse.error(500, "系统异常，请稍后重试");
        }
    }

    /**
     * 刷新访问令牌
     * 
     * @param dto 令牌DTO
     * @return 新的令牌信息
     */
    @PostMapping("/refresh-token")
    @Operation(summary = "刷新访问令牌", description = "使用刷新令牌获取新的访问令牌")
    public ApiResponse<TokenVO> refreshToken(@Valid @RequestBody TokenDTO dto) {
        try {
            TokenVO tokenVO = userService.refreshToken(dto);
            log.info("令牌刷新成功: clientId={}, grantType={}, tenantId={}", dto.getClientId(), dto.getGrantType(), dto.getTenantId());
            return ApiResponse.success(tokenVO);
        } catch (BusinessException e) {
            log.error("令牌刷新失败: clientId={}, grantType={}, tenantId={}, error={}", dto.getClientId(), dto.getGrantType(), dto.getTenantId(), e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("令牌刷新异常: clientId={}, grantType={}, tenantId={}, error={}", dto.getClientId(), dto.getGrantType(), dto.getTenantId(), e.getMessage(), e);
            return ApiResponse.error(500, "系统异常，请稍后重试");
        }
    }

    /**
     * 验证访问令牌
     * 
     * @param accessToken 访问令牌
     * @param tenantId 租户ID
     * @return 验证结果
     */
    @GetMapping("/validate-token")
    @Operation(summary = "验证访问令牌", description = "验证访问令牌的有效性")
    public ApiResponse<Boolean> validateToken(
            @Parameter(description = "访问令牌", required = true)
            @RequestParam("accessToken") String accessToken,
            @Parameter(description = "租户ID", required = true)
            @RequestParam("tenantId") @NotNull @Min(1) Long tenantId) {
        try {
            Boolean isValid = userService.validateToken(accessToken, tenantId);
            log.info("令牌验证完成: tenantId={}, isValid={}", tenantId, isValid);
            return ApiResponse.success(isValid);
        } catch (BusinessException e) {
            log.error("令牌验证失败: tenantId={}, error={}", tenantId, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("令牌验证异常: tenantId={}, error={}", tenantId, e.getMessage(), e);
            return ApiResponse.error(500, "系统异常，请稍后重试");
        }
    }

    /**
     * 创建用户
     * 
     * @param dto 用户创建DTO
     * @return 用户ID
     */
    @PostMapping("/create")
    @Operation(summary = "创建用户", description = "创建新用户，支持多租户隔离")
    public ApiResponse<Long> createUser(@Valid @RequestBody UserCreateDTO dto) {
        try {
            Long userId = userService.createUser(dto);
            log.info("用户创建成功: userId={}, username={}, tenantId={}", userId, dto.getUsername(), dto.getTenantId());
            return ApiResponse.success(userId);
        } catch (BusinessException e) {
            log.error("创建用户失败: username={}, tenantId={}, error={}", dto.getUsername(), dto.getTenantId(), e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("创建用户异常: username={}, tenantId={}, error={}", dto.getUsername(), dto.getTenantId(), e.getMessage(), e);
            return ApiResponse.error(500, "系统异常，请稍后重试");
        }
    }

    /**
     * 更新用户信息
     * 
     * @param dto 用户更新DTO
     * @return 更新结果
     */
    @PutMapping("/update")
    @Operation(summary = "更新用户", description = "更新用户信息，支持多租户隔离")
    public ApiResponse<Boolean> updateUser(@Valid @RequestBody UserUpdateDTO dto) {
        try {
            Boolean result = userService.updateUser(dto);
            log.info("用户更新成功: userId={}, tenantId={}", dto.getId(), dto.getTenantId());
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("更新用户失败: userId={}, tenantId={}, error={}", dto.getId(), dto.getTenantId(), e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("更新用户异常: userId={}, tenantId={}, error={}", dto.getId(), dto.getTenantId(), e.getMessage(), e);
            return ApiResponse.error(500, "系统异常，请稍后重试");
        }
    }

    /**
     * 删除用户
     * 
     * @param id 用户ID
     * @param tenantId 租户ID
     * @return 删除结果
     */
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除用户", description = "根据ID删除用户，支持多租户隔离")
    public ApiResponse<Boolean> deleteUser(
            @Parameter(description = "用户ID", required = true)
            @PathVariable("id") @NotNull @Min(1) Long id,
            @Parameter(description = "租户ID", required = true)
            @RequestParam("tenantId") @NotNull @Min(1) Long tenantId) {
        try {
            Boolean result = userService.deleteUser(id, tenantId);
            log.info("用户删除成功: userId={}, tenantId={}", id, tenantId);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("删除用户失败: userId={}, tenantId={}, error={}", id, tenantId, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("删除用户异常: userId={}, tenantId={}, error={}", id, tenantId, e.getMessage(), e);
            return ApiResponse.error(500, "系统异常，请稍后重试");
        }
    }

    /**
     * 批量删除用户
     * 
     * @param userIds 用户ID列表
     * @param tenantId 租户ID
     * @return 删除结果
     */
    @DeleteMapping("/batch-delete")
    @Operation(summary = "批量删除用户", description = "批量删除用户，支持多租户隔离")
    public ApiResponse<Boolean> batchDeleteUsers(
            @Parameter(description = "用户ID列表", required = true)
            @RequestBody List<Long> userIds,
            @Parameter(description = "租户ID", required = true)
            @RequestParam("tenantId") @NotNull @Min(1) Long tenantId) {
        try {
            Boolean result = userService.batchDeleteUsers(userIds, tenantId);
            log.info("批量删除用户成功: userIds={}, tenantId={}", userIds, tenantId);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("批量删除用户失败: userIds={}, tenantId={}, error={}", userIds, tenantId, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("批量删除用户异常: userIds={}, tenantId={}, error={}", userIds, tenantId, e.getMessage(), e);
            return ApiResponse.error(500, "系统异常，请稍后重试");
        }
    }

    /**
     * 根据ID查询用户详情
     * 
     * @param id 用户ID
     * @param tenantId 租户ID
     * @return 用户详情
     */
    @GetMapping("/get/{id}")
    @Operation(summary = "查询用户详情", description = "根据ID查询用户详情，支持多租户隔离")
    public ApiResponse<UserVO> getUserById(
            @Parameter(description = "用户ID", required = true)
            @PathVariable("id") @NotNull @Min(1) Long id,
            @Parameter(description = "租户ID", required = true)
            @RequestParam("tenantId") @NotNull @Min(1) Long tenantId) {
        try {
            UserVO userVO = userService.getUserById(id, tenantId);
            return ApiResponse.success(userVO);
        } catch (BusinessException e) {
            log.error("查询用户详情失败: userId={}, tenantId={}, error={}", id, tenantId, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("查询用户详情异常: userId={}, tenantId={}, error={}", id, tenantId, e.getMessage(), e);
            return ApiResponse.error(500, "系统异常，请稍后重试");
        }
    }

    /**
     * 分页查询用户列表
     * 
     * @param queryDTO 查询条件
     * @return 分页用户列表
     */
    @PostMapping("/page")
    @Operation(summary = "分页查询用户", description = "分页查询用户列表，支持多租户隔离和多条件筛选")
    public ApiResponse<PageResponse<UserListVO>> getUserPage(@Valid @RequestBody UserQueryDTO queryDTO) {
        try {
            IPage<UserListVO> userPage = userService.getUserPage(queryDTO);
            PageResponse<UserListVO> pageResponse = PageResponse.of(userPage);
            return ApiResponse.success(pageResponse);
        } catch (BusinessException e) {
            log.error("分页查询用户失败: tenantId={}, error={}", queryDTO.getTenantId(), e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("分页查询用户异常: tenantId={}, error={}", queryDTO.getTenantId(), e.getMessage(), e);
            return ApiResponse.error(500, "系统异常，请稍后重试");
        }
    }

    /**
     * 查询用户列表
     * 
     * @param queryDTO 查询条件
     * @return 用户列表
     */
    @PostMapping("/list")
    @Operation(summary = "查询用户列表", description = "查询用户列表，支持多租户隔离和多条件筛选")
    public ApiResponse<List<UserListVO>> getUserList(@Valid @RequestBody UserQueryDTO queryDTO) {
        try {
            List<UserListVO> userList = userService.getUserList(queryDTO);
            return ApiResponse.success(userList);
        } catch (BusinessException e) {
            log.error("查询用户列表失败: tenantId={}, error={}", queryDTO.getTenantId(), e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("查询用户列表异常: tenantId={}, error={}", queryDTO.getTenantId(), e.getMessage(), e);
            return ApiResponse.error(500, "系统异常，请稍后重试");
        }
    }

    /**
     * 启用用户
     * 
     * @param id 用户ID
     * @param tenantId 租户ID
     * @return 操作结果
     */
    @PutMapping("/enable/{id}")
    @Operation(summary = "启用用户", description = "启用用户，支持多租户隔离")
    public ApiResponse<Boolean> enableUser(
            @Parameter(description = "用户ID", required = true)
            @PathVariable("id") @NotNull @Min(1) Long id,
            @Parameter(description = "租户ID", required = true)
            @RequestParam("tenantId") @NotNull @Min(1) Long tenantId) {
        try {
            // 这里暂时使用tenantId作为operatorId，实际应该从当前登录用户获取
            Boolean result = userService.enableUser(id, tenantId, tenantId);
            log.info("启用用户成功: userId={}, tenantId={}", id, tenantId);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("启用用户失败: userId={}, tenantId={}, error={}", id, tenantId, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("启用用户异常: userId={}, tenantId={}, error={}", id, tenantId, e.getMessage(), e);
            return ApiResponse.error(500, "系统异常，请稍后重试");
        }
    }

    /**
     * 禁用用户
     * 
     * @param id 用户ID
     * @param tenantId 租户ID
     * @return 操作结果
     */
    @PutMapping("/disable/{id}")
    @Operation(summary = "禁用用户", description = "禁用用户，支持多租户隔离")
    public ApiResponse<Boolean> disableUser(
            @Parameter(description = "用户ID", required = true)
            @PathVariable("id") @NotNull @Min(1) Long id,
            @Parameter(description = "租户ID", required = true)
            @RequestParam("tenantId") @NotNull @Min(1) Long tenantId) {
        try {
            // 这里暂时使用tenantId作为operatorId，实际应该从当前登录用户获取
            Boolean result = userService.disableUser(id, tenantId, tenantId);
            log.info("禁用用户成功: userId={}, tenantId={}", id, tenantId);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("禁用用户失败: userId={}, tenantId={}, error={}", id, tenantId, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("禁用用户异常: userId={}, tenantId={}, error={}", id, tenantId, e.getMessage(), e);
            return ApiResponse.error(500, "系统异常，请稍后重试");
        }
    }

    /**
     * 批量更新用户状态
     * 
     * @param userIds 用户ID列表
     * @param status 用户状态
     * @param tenantId 租户ID
     * @return 操作结果
     */
    @PutMapping("/batch-status")
    @Operation(summary = "批量更新用户状态", description = "批量更新用户状态，支持多租户隔离")
    public ApiResponse<Boolean> batchUpdateUserStatus(
            @Parameter(description = "用户ID列表", required = true)
            @RequestParam("userIds") List<Long> userIds,
            @Parameter(description = "用户状态", required = true)
            @RequestParam("status") Integer status,
            @Parameter(description = "租户ID", required = true)
            @RequestParam("tenantId") @NotNull @Min(1) Long tenantId) {
        try {
            // 将Integer状态转换为UserStatus枚举
            UserStatus userStatus = UserStatus.getByCode(status);
            // 这里暂时使用tenantId作为operatorId，实际应该从当前登录用户获取
            Boolean result = userService.batchUpdateUserStatus(userIds, userStatus, tenantId, tenantId);
            log.info("批量更新用户状态成功: userIds={}, status={}, tenantId={}", userIds, status, tenantId);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("批量更新用户状态失败: userIds={}, status={}, tenantId={}, error={}", userIds, status, tenantId, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("批量更新用户状态异常: userIds={}, status={}, tenantId={}, error={}", userIds, status, tenantId, e.getMessage(), e);
            return ApiResponse.error(500, "系统异常，请稍后重试");
        }
    }

    /**
     * 重置用户密码
     * 
     * @param id 用户ID
     * @param newPassword 新密码
     * @param tenantId 租户ID
     * @return 操作结果
     */
    @PutMapping("/reset-password/{id}")
    @Operation(summary = "重置用户密码", description = "重置用户密码，支持多租户隔离")
    public ApiResponse<Boolean> resetPassword(
            @Parameter(description = "用户ID", required = true)
            @PathVariable("id") @NotNull @Min(1) Long id,
            @Parameter(description = "新密码", required = true)
            @RequestParam("newPassword") String newPassword,
            @Parameter(description = "租户ID", required = true)
            @RequestParam("tenantId") @NotNull @Min(1) Long tenantId) {
        try {
            // 这里暂时使用tenantId作为operatorId，实际应该从当前登录用户获取
            Boolean result = userService.resetPassword(id, newPassword, tenantId, tenantId);
            log.info("重置用户密码成功: userId={}, tenantId={}", id, tenantId);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("重置用户密码失败: userId={}, tenantId={}, error={}", id, tenantId, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("重置用户密码异常: userId={}, tenantId={}, error={}", id, tenantId, e.getMessage(), e);
            return ApiResponse.error(500, "系统异常，请稍后重试");
        }
    }

    /**
     * 修改用户密码
     * 
     * @param id 用户ID
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @param tenantId 租户ID
     * @return 操作结果
     */
    @PutMapping("/change-password/{id}")
    @Operation(summary = "修改用户密码", description = "修改用户密码，需要验证旧密码")
    public ApiResponse<Boolean> changePassword(
            @Parameter(description = "用户ID", required = true)
            @PathVariable("id") @NotNull @Min(1) Long id,
            @Parameter(description = "旧密码", required = true)
            @RequestParam("oldPassword") String oldPassword,
            @Parameter(description = "新密码", required = true)
            @RequestParam("newPassword") String newPassword,
            @Parameter(description = "租户ID", required = true)
            @RequestParam("tenantId") @NotNull @Min(1) Long tenantId) {
        try {
            Boolean result = userService.changePassword(id, oldPassword, newPassword, tenantId);
            log.info("修改用户密码成功: userId={}, tenantId={}", id, tenantId);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("修改用户密码失败: userId={}, tenantId={}, error={}", id, tenantId, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("修改用户密码异常: userId={}, tenantId={}, error={}", id, tenantId, e.getMessage(), e);
            return ApiResponse.error(500, "系统异常，请稍后重试");
        }
    }

    /**
     * 检查用户名是否存在
     * 
     * @param username 用户名
     * @param tenantId 租户ID
     * @return 是否存在
     */
    @GetMapping("/check-username")
    @Operation(summary = "检查用户名是否存在", description = "检查用户名是否存在，支持多租户隔离")
    public ApiResponse<Boolean> checkUsernameExists(
            @Parameter(description = "用户名", required = true)
            @RequestParam("username") String username,
            @Parameter(description = "租户ID", required = true)
            @RequestParam("tenantId") @NotNull @Min(1) Long tenantId) {
        try {
            Boolean exists = userService.checkUsernameExists(username, null, tenantId);
            return ApiResponse.success(exists);
        } catch (BusinessException e) {
            log.error("检查用户名失败: username={}, tenantId={}, error={}", username, tenantId, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("检查用户名异常: username={}, tenantId={}, error={}", username, tenantId, e.getMessage(), e);
            return ApiResponse.error(500, "系统异常，请稍后重试");
        }
    }

    /**
     * 检查邮箱是否存在
     * 
     * @param email 邮箱
     * @param tenantId 租户ID
     * @return 是否存在
     */
    @GetMapping("/check-email")
    @Operation(summary = "检查邮箱是否存在", description = "检查邮箱是否存在，支持多租户隔离")
    public ApiResponse<Boolean> checkEmailExists(
            @Parameter(description = "邮箱", required = true)
            @RequestParam("email") String email,
            @Parameter(description = "租户ID", required = true)
            @RequestParam("tenantId") @NotNull @Min(1) Long tenantId) {
        try {
            Boolean exists = userService.checkEmailExists(email, null, tenantId);
            return ApiResponse.success(exists);
        } catch (BusinessException e) {
            log.error("检查邮箱失败: email={}, tenantId={}, error={}", email, tenantId, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("检查邮箱异常: email={}, tenantId={}, error={}", email, tenantId, e.getMessage(), e);
            return ApiResponse.error(500, "系统异常，请稍后重试");
        }
    }

    /**
     * 检查手机号是否存在
     * 
     * @param phone 手机号
     * @param tenantId 租户ID
     * @return 是否存在
     */
    @GetMapping("/check-phone")
    @Operation(summary = "检查手机号是否存在", description = "检查手机号是否存在，支持多租户隔离")
    public ApiResponse<Boolean> checkPhoneExists(
            @Parameter(description = "手机号", required = true)
            @RequestParam("phone") String phone,
            @Parameter(description = "租户ID", required = true)
            @RequestParam("tenantId") @NotNull @Min(1) Long tenantId) {
        try {
            Boolean exists = userService.checkPhoneExists(phone, null, tenantId);
            return ApiResponse.success(exists);
        } catch (BusinessException e) {
            log.error("检查手机号失败: phone={}, tenantId={}, error={}", phone, tenantId, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("检查手机号异常: phone={}, tenantId={}, error={}", phone, tenantId, e.getMessage(), e);
            return ApiResponse.error(500, "系统异常，请稍后重试");
        }
    }

    /**
     * 统计用户数量
     * 
     * @param queryDTO 查询条件
     * @return 用户数量
     */
    @PostMapping("/count")
    @Operation(summary = "统计用户数量", description = "统计用户数量，支持多租户隔离和多条件筛选")
    public ApiResponse<Long> countUsers(@Valid @RequestBody UserQueryDTO queryDTO) {
        try {
            Long count = userService.countUsers(queryDTO);
            return ApiResponse.success(count);
        } catch (BusinessException e) {
            log.error("统计用户数量失败: tenantId={}, error={}", queryDTO.getTenantId(), e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("统计用户数量异常: tenantId={}, error={}", queryDTO.getTenantId(), e.getMessage(), e);
            return ApiResponse.error(500, "系统异常，请稍后重试");
        }
    }

    /**
     * 根据租户ID查询用户列表
     * 
     * @param tenantId 租户ID
     * @return 用户列表
     */
    @GetMapping("/tenant/{tenantId}")
    @Operation(summary = "根据租户ID查询用户列表", description = "根据租户ID查询用户列表")
    public ApiResponse<List<UserListVO>> getUsersByTenantId(
            @Parameter(description = "租户ID", required = true)
            @PathVariable("tenantId") @NotNull @Min(1) Long tenantId) {
        try {
            List<User> users = userService.getUsersByTenantId(tenantId);
            // 转换为VO对象
            List<UserListVO> userList = users.stream()
                .map(user -> {
                    UserListVO vo = new UserListVO();
                    vo.setId(user.getId());
                    vo.setUsername(user.getUsername());
                    vo.setRealName(user.getRealName());
                    vo.setEmail(user.getEmail());
                    vo.setPhone(user.getPhone());
                    vo.setAvatar(user.getAvatar());
                    vo.setStatus(user.getStatus() != null ? user.getStatus().name() : null);
                    vo.setTenantId(user.getTenantId());
                    vo.setCreateTime(user.getCreateTime());
                    vo.setUpdateTime(user.getUpdateTime());
                    vo.setLastLoginTime(user.getLastLoginTime());
                    vo.setLoginCount(user.getLoginCount());
                    return vo;
                })
                .collect(java.util.stream.Collectors.toList());
            return ApiResponse.success(userList);
        } catch (BusinessException e) {
            log.error("根据租户ID查询用户列表失败: tenantId={}, error={}", tenantId, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("根据租户ID查询用户列表异常: tenantId={}, error={}", tenantId, e.getMessage(), e);
            return ApiResponse.error(500, "系统异常，请稍后重试");
        }
    }
}